import os
import re

def count_lines_in_file(file_path):
    """
    统计单个 .ets 文件的代码行数。
    :param file_path: 文件路径
    :return: (total_lines, code_lines, comment_lines)
    """
    total_lines = 0
    code_lines = 0
    comment_lines = 0
    in_multiline_comment = False

    with open(file_path, 'r', encoding='utf-8') as file:
        for line in file:
            total_lines += 1
            stripped_line = line.strip()

            # 检查是否在多行注释中
            if in_multiline_comment:
                comment_lines += 1
                if re.search(r'\*/', stripped_line):  # 多行注释结束
                    in_multiline_comment = False
                continue

            # 检查多行注释开始
            if re.search(r'/\*', stripped_line):
                in_multiline_comment = True
                comment_lines += 1
                if re.search(r'\*/', stripped_line):  # 单行内的多行注释 /* ... */
                    in_multiline_comment = False
                continue

            # 检查单行注释
            if stripped_line.startswith('//'):
                comment_lines += 1
                continue

            # 检查空行或仅包含空格的行
            if not stripped_line:
                continue

            # 剩余的是代码行
            code_lines += 1

    return total_lines, code_lines, comment_lines


def count_lines_in_directory(directory):
    """
    遍历目录下的所有 .ets 文件并统计代码行数。
    :param directory: 目录路径
    :return: 总计的 (total_lines, code_lines, comment_lines)
    """
    total_lines = 0
    code_lines = 0
    comment_lines = 0

    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.ets'):
                file_path = os.path.join(root, file)
                t, c, m = count_lines_in_file(file_path)
                total_lines += t
                code_lines += c
                comment_lines += m
                print(f"File: {file_path} -> Total: {t}, Code: {c}, Comments: {m}")

    return total_lines, code_lines, comment_lines


if __name__ == '__main__':
    target_directory = input("请输入要统计的目录路径：").strip()
    if os.path.isdir(target_directory):
        total, code, comments = count_lines_in_directory(target_directory)
        print("\n统计结果：")
        print(f"总行数: {total}")
        print(f"代码行数: {code}")
        print(f"注释行数: {comments}")
    else:
        print("输入的路径无效，请检查后重试！")
